<?php
/**
 * NfxPartnerLevelModel.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */
namespace  addons\Nsfx\data\model;

use data\model\BaseModel as BaseModel;
use data\model\NsMemberModel;
use data\model\NsOrderModel;
use data\service\Member;
use data\service\OrderCreate;
use think\Db;

/**
 * 订单模型
 * 奖励佣金=（平台销售价-成本）*80%
 */
class NfxOrderModel extends BaseModel {

    protected $table = 'nfx_order';

    /**
     * 获取订单的佣金基数
    */
    private function get_cost_price($order_id, $goods_type = 'is_direct_award', $return_goods_id = false)
    {
        $goods_id = [];
        $cost_price = 0;
        $order_goods = Db::name('ns_order_goods')->where(['order_id' => $order_id])->select();
        foreach ($order_goods as $item) {
            $goods = Db::name('ns_goods')->where(['goods_id' => $item['goods_id']])->find();
            if ($goods_type === true) {
                $is_include = true;
            } else {
                $is_include = Db::name('ns_goods_category')->where(['category_id' => $goods['category_id']])->value($goods_type);
            }
            if ($is_include) {
                $cost_price += $item['cost_price'] * $item['num'];//减掉成本
            }

            if ($return_goods_id) {
                $goods_id[] = $item['goods_id'];
            }
        }

        if ($return_goods_id) {
            return ['cost_price' => $cost_price, 'goods_ids' => $goods_id];
        } else {
            return $cost_price;
        }
    }

    /**
     * 插入收益记录
    */
    private function insert_nfx_distribution($order_id, $reward, $income_uid, $buyer_id, $reward_type = 1)
    {
        $order_goods = Db::name('ns_order_goods')->where(['order_id' => $order_id])->find();
        $commossion_distribution = new NfxCommissionDistributionModel();
        $data = array(
            'serial_no' => getSerialNo(),
            'shop_id' => 0,
            'income_uid' => $income_uid,
            'promoter_id' => $buyer_id,
            'promoter_level' => 0,
            'order_id' => $order_id,
            'order_goods_id' => $order_goods['order_goods_id'],
            'goods_money' => $order_goods['goods_money'],
            'goods_cost' => $order_goods['cost_price'],
            'goods_return' => 0,//折扣
            'goods_commission_rate' => 0,
            'commission_rate' => 0,
            'commission_money' => $reward,
            'create_time' => time(),
            'is_issue' => 1,
            'reward_type' => $reward_type,//分享佣金,public $reward_type = [1 => '分享佣金', 2 => '培育奖励', 3 => '团队奖励', 4 => '极差奖', 5 => '全网分红', 6 => 平级奖, 7 => 冲单奖, 8 => 折扣返金币];
        );

        $commossion_distribution->save($data);
    }

    //冲单奖
    public function rush_hour_reward($order_id)
    {
        $cost_price_info = $this->get_cost_price($order_id, 'is_rush_hour', true);//成本价
        if ($cost_price_info['cost_price'] > 0) {
            $order_info = (new NsOrderModel())->get($order_id);
            $base_num = $order_info['order_money'] - $cost_price_info['cost_price'];
            if ($base_num > 0) {
                $self_reward = 0;
                $self_order_goods = [];
                foreach ($cost_price_info['goods_ids'] as $key => $goods_id) {
                    $self_order_goods[$key]['goods_id'] = $goods_id;
                    $self_order_goods[$key]['count'] = Db::name('ns_order_goods')->where(['goods_id' => $goods_id, 'buyer_id' => $order_info['buyer_id']])->count();
                }
                foreach ($self_order_goods as $goods) {
                    $rush_hour_list = Db::name('ns_goods_rush_hour_preferential')->where(['goods_id' => $goods['goods_id']])->select();
                    foreach ($rush_hour_list as $item) {
                        if ($goods['count'] >= $item['quantity']) {
                            $self_reward = $item['reward'];
                        }
                    }
                }

                //自己购买有冲单奖
                if ($self_reward > 0) {
                    $memberAccount = new Member\MemberAccount();
                    $retval = $memberAccount->addMemberAccountData(0, 2, $order_info['buyer_id'], 1, $self_reward, 1, $order_id, '获得冲单奖');

                    //插入收益记录，以供后台前台查询
                    if ($retval) {
                        $commossion_distribution = new NfxCommissionDistributionModel();
                        $this->insert_nfx_distribution($order_id, $self_reward, $order_info['buyer_id'], $order_info['buyer_id'], $commossion_distribution->reward_type_id('rush_hour_reward'));//冲单奖
                    }
                }

                //自己购买上级有冲单奖
                $parent_id = Db::name('ns_member')->where(['uid' => $order_info['buyer_id']])->value('parent_id');
                if ($parent_id > 0) {
                    $parent_reward = 0;
                    $son_rush_hour_num = 0;
                    $sons = Db::name('ns_member')->where(['parent_id' => $parent_id])->field('uid')->select();
                    foreach ($sons as $son) {
                        foreach ($self_order_goods as $goods) {
                            $son_rush_hour_num += Db::name('nfx_commission_distribution')->where(['income_uid' => $son['uid'], 'reward_type' => 7, 'order_goods_id' => $goods['goods_id']])->count();
                        }
                    }

                    if ($son_rush_hour_num > 0) {
                        foreach ($self_order_goods as $goods) {
                            $rush_hour_list = Db::name('ns_goods_rush_hour_preferential')->where(['goods_id' => $goods['goods_id']])->select();
                            foreach ($rush_hour_list as $item) {
                                if ($goods['count'] >= $item['quantity']) {
                                    $parent_reward = $item['reward'];
                                }
                            }
                        }
                    }

                    if ($parent_reward > 0) {
                        $memberAccount = new Member\MemberAccount();
                        $retval = $memberAccount->addMemberAccountData(0, 2, $parent_id, 1, $parent_reward, 1, $order_id, '获得直推冲单奖');

                        //插入收益记录，以供后台前台查询
                        if ($retval) {
                            $this->insert_nfx_distribution($order_id, $parent_reward, $parent_id, $order_info['buyer_id'], $commossion_distribution->reward_type_id('rush_hour_reward'));//冲单奖
                        }
                    }
                }
            }
        }
    }

    //直推奖 20220316
    public function invite_reward($order_id)
    {
        $cost_price = $this->get_cost_price($order_id, 'is_direct_award');//成本价

        if ($cost_price > 0) {
            $order_info = (new NsOrderModel())->get($order_id);
            $parent = (new Member())->getMemberInfo(['uid'=>$order_info['buyer_id']],"parent_id");
            if (isset($parent['parent_id'])) {
                $lv = Db::name('ns_member')->where(['uid' => $parent['parent_id']])->value('member_level');
                $direct_ratio = Db::name('ns_member_level')->where(['level' => $lv])->value('first_rate');
                $reward = $direct_ratio * 0.01 * ($order_info['order_money'] - $cost_price);
                if ($reward > 0) {
                    $memberAccount = new Member\MemberAccount();
                    $retval = $memberAccount->addMemberAccountData(0, 2, $parent['parent_id'], 1, $reward, 1, $order_id, '获得直推奖');

                    //插入收益记录，以供后台前台查询
                    if ($retval) {
                        $this->insert_nfx_distribution($order_id, $reward, $parent['parent_id'], $order_info['buyer_id'], 1);//推荐奖
                    }
                }
            }
        }
    }

    /**
     * 培育奖
     * 培育奖总奖金=订单金额-成本-直推奖
     * 如：A-B-C一D，D购买了 398元商品，C是店长获得直推奖10%，B获得培育奖总奖金的一半，A获得培育奖总奖金一半的一半，直至0.1元終止
    */
    public function teach_reward($order_id)
    {
        $commossion_distribution = new NfxCommissionDistributionModel();
        $direct_reward = $commossion_distribution->getColumn('order_id=' . $order_id . ' and reward_type=1', 'commission_money');
        $direct_reward = $direct_reward[0] ?: 0;
        if ($direct_reward <= 0) {
            return;
        }

        $buyer_id = Db::name('ns_order')->where(['order_id' => $order_id])->value('buyer_id');
        $userinfo = Db::name('ns_member')->where(['uid' => $buyer_id])->find();
        if ($userinfo['tree']) {
            $order_info = (new NsOrderModel())->get($order_id);
            $cost_price = $this->get_cost_price($order_id, 'is_direct_award');//成本价
            $teach_reward = $order_info['order_money'] - $cost_price - $direct_reward;
            $memberAccount = new Member\MemberAccount();
            $tree = ltrim(rtrim($userinfo['tree'], ','), ',');
            $tree_arr = array_reverse(explode(',', $tree));
            foreach ($tree_arr as $key => $item) {
                if ($key > 0) {//除去直推，培育奖从第二个开始
                    $level = Db::name('ns_member')->where(['uid' => $item])->value('member_level');
                    $level_ratio = Db::name('ns_member_level')->where(['level' => $level])->value('down_rate');
                    $div = pow(2, $key - 1);
                    $reward = $teach_reward * $level_ratio * 0.01 / $div;
                    if ($reward > 0.1) {
                        $retval = $memberAccount->addMemberAccountData(0, 2, $item, 1, $reward, 1, $order_id, '获得培育奖');
                        if ($retval) {
                            $this->insert_nfx_distribution($order_id, $reward, $item, $buyer_id, 2);//培育奖
                        }
                    }
                }
            }
        }
    }

    /**
     * 团队奖【级差奖】
    */
    public function team_reward($order_id)
    {
        $cost_price = $this->get_cost_price($order_id, 'is_differential');//成本价
        if ($cost_price > 0) {
            $order_info = (new NsOrderModel())->get($order_id);
            $base_num = $order_info['order_money'] - $cost_price;

            $memberAccount = new Member\MemberAccount();
            $buyer_id = Db::name('ns_order')->where(['order_id' => $order_id])->value('buyer_id');
            $users = NsMemberModel::find_team_award_users($order_info['buyer_id']);
            $last_team_reward = 0;
            foreach ($users as $user) {
                $reward = $base_num * $user['award_rate'] * 0.01;
                if ($reward > 0) {
                    $last_team_reward = $reward;//为平级奖作准备
                    $retval = $memberAccount->addMemberAccountData(0, 2, $user['user_id'], 1, $reward, 1, $order_id, '获得级差奖');
                    if ($retval) {
                        $this->insert_nfx_distribution($order_id, $reward, $user['user_id'], $buyer_id, 4);//极差奖
                    }
                }

                if ($user['same_lv_rate'] > 0 && $last_team_reward) {
                    $same_lv_reward = $last_team_reward * $user['same_lv_rate'] * 0.01;
                    if ($same_lv_reward > 0) {
                        $retval = $memberAccount->addMemberAccountData(0, 2, $user['user_id'], 1, $same_lv_reward, 1, $order_id, '获得平级奖');
                        if ($retval) {
                            $this->insert_nfx_distribution($order_id, $same_lv_reward, $user['user_id'], $buyer_id, 6);//平级奖
                        }
                    }
                }
            }
        }
    }

    /**
     * 全网分红
     * 这里先暂存至一个字段，到固定时间再分
    */
    public function leader_reward($order_id)
    {
        $cost_price = $this->get_cost_price($order_id, true);//成本价
        if ($cost_price > 0) {
            $order_info = (new NsOrderModel())->get($order_id);
            $base_num = $order_info['order_money'] - $cost_price;
            Db::name('sys_config')->where(['instance_id' => 0, 'key' => 'LEADER_POOL'])->setInc('value', $base_num);
        }
    }

    /**
     * 扣外返金币，比如商品8折，剩余的2折返给用户金币
    */
    public function discount_reback($order_info)
    {
        $goods_id = $order_info["order_goods_list"][0]->goods_id ?? 0;
        if ($goods_id == 0) {
            return 1;
        }
        $order_create = new OrderCreate();
        $goods_member_discount = $order_create->getGoodsMemberDiscount($order_info['buyer_id'], $goods_id);
        if ($goods_member_discount < 1) {
            $source_price = $order_info['order_money'] / $goods_member_discount;
            $reward = $source_price * (1 - $goods_member_discount);
            if ($reward > 0) {
                $memberAccount = new Member\MemberAccount();
                $retval = $memberAccount->addMemberAccountData(0, 2, $order_info['buyer_id'], 1, $reward, 1, $order_info['order_id'], '获得折扣返金币');
                if ($retval) {
                    $this->insert_nfx_distribution($order_info['order_id'], $retval, $order_info['buyer_id'], $order_info['buyer_id'], 8);//返折扣
                }
            }
        }
    }
}
